package com.voicechat.firstmet.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @class name：com.je.utils
 * @class describe
 * @Description
 * @anthor ljp
 * @time 2017/3/31 0031 下午 02:23
 */
public class ImageUtils {

        /**
         * Get bitmap from specified image path
         *
         * @param imgPath
         * @return
         */
        public Bitmap getBitmap(String imgPath) {
            // Get bitmap through image path
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = false;
            newOpts.inPurgeable = true;
            newOpts.inInputShareable = true;
            // Do not compress
            newOpts.inSampleSize = 1;
            newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
            return BitmapFactory.decodeFile(imgPath, newOpts);
        }

    /**
     * 将图片变为圆角
     *
     * @param bitmap
     *            原Bitmap图片
     * @param pixels
     *            图片圆角的弧度(单位:像素(px))
     * @return 带有圆角的图片(Bitmap 类型)
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * drawable转bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable, int px) {
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(px, px, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, px, px);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
//        Log.i("ImageUtils", "compressImage: baos.toByteArray().length+"+baos.toByteArray().length);
        while ((baos.toByteArray().length / 1024) > 1024 ) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩options%，把压缩后的数据存放到baos中
//            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        newOpts.
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }


    /***
     * 压缩读取本地图片
     *
     * @param path
     * @param context
     * @return
     */
    public static Bitmap DecodLocalFileImage(String path, Context context) {
        int dw = ScreenUtils.getScreenWidth(context);
        int dh = ScreenUtils.getScreenHeight(context);
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh);
        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw);
        if (heightRatio > 1 && widthRatio > 1) {
            bmpFactoryOptions.inSampleSize = heightRatio;
        } else {
            bmpFactoryOptions.inSampleSize = widthRatio;
        }
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
        return bmp;
    }
    public static Bitmap compressImageToBitmap(Bitmap bmp) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 200) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();//重置baos即清空baos
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 720f;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = 720f;// 设置宽度为120f，可以明显看到图片缩小了
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        Log.i("imageUtils", "compressImageToBitmap: --be--"+be);
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if(baos.toByteArray().length / 1024 > 1024){
            Log.i("imageUtils", "compressImageToBitmap: --length--"+os.toByteArray().length);
            return compressBitmapToFile(bitmap);
        }else{
            return bitmap;
        }
        //压缩好比例大小后再进行质量压缩
//      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
    }
    /**
     * 2. 尺寸压缩
     * 通过缩放图片像素来减少图片占用内存大小
     * @param bmp
     *
     */
    public static Bitmap compressBitmapToFile(Bitmap bmp) {
        // 尺寸压缩倍数,值越大，图片尺寸越小
        int ratio = 5;
        // 压缩Bitmap到对应尺寸
        Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);
        canvas.drawBitmap(bmp, null, rect, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        result.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);
    }
    /**
         * Store bitmap into specified image path
         *
         * @param bitmap
         * @param outPath
         * @throws FileNotFoundException
         */
        public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
            FileOutputStream os = new FileOutputStream(outPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        }

        /**
         * Compress image by pixel, this will modify image width/height.
         * Used to get thumbnail
         *
         * @param imgPath image path
         * @param pixelW target pixel of width
         * @param pixelH target pixel of height
         * @return
         */
        public static Bitmap ratio(String imgPath, float pixelW, float pixelH) {
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true，即只读边不读内容
            newOpts.inJustDecodeBounds = true;
            newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
            // Get bitmap info, but notice that bitmap is null now
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);

            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            // 想要缩放的目标尺寸
            float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
            float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
            // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;//be=1表示不缩放
            if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
                be = (int) (newOpts.outWidth / ww);
            } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
                be = (int) (newOpts.outHeight / hh);
            }
            if (be <= 0) be = 1;
            newOpts.inSampleSize = be;//设置缩放比例
            // 开始压缩图片，注意此时已经把options.inJustDecodeBounds 设回false了
            bitmap = BitmapFactory.decodeFile(imgPath, newOpts);

            // 压缩好比例大小后再进行质量压缩
//        return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
            return bitmap;
//            return compressImage(bitmap);
        }


    /**
     * Compress image by pixel, this will modify image width/height.
     * Used to get thumbnail
     * 伪精确压缩，保证压缩值小于等于目标值
     * @param imgPath image path
     * @param pixelW target pixel of width
     * @param pixelH target pixel of height
     * @return
     */
    public static Bitmap ratioAccurate(String imgPath, float pixelW, float pixelH) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true，即只读边不读内容
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        // Get bitmap info, but notice that bitmap is null now
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;//原图宽像素点
        int h = newOpts.outHeight;//原图高像素点
        // 想要缩放的目标尺寸
        float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        float be = 1;//计算实际比率
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = newOpts.outWidth / ww;
            Log.i("AAA", "ratio: "+be);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = newOpts.outHeight / hh;
        }
        //inSampleSize 好像是2的N次方，那么无论你给它赋值为多少，它默认会找一个最接近的2的N次方的整数。
        //比如我们给inSampleSize是赋值为5，那么系统中他的实际值为4
        //下面我们通过计算向上取2的N次方为inSampleSize的值（比如大于4小于8的我们都取8）
        double log = Math.log(be) / Math.log(2);
        double logCeil = Math.ceil(log);
        int size = (int) Math.pow(2, logCeil);//缩放尺寸
        newOpts.inSampleSize = size;//设置缩放比例
        // 开始压缩图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
        // 压缩好比例大小后再进行质量压缩
        return bitmap;
    }

    public static Bitmap comp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if ((baos.toByteArray().length / 1024) > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为 ,我们的目的是压缩头像 没必要那么大
        float hh = 720f;//这里设置高度为800f
        float ww = 1080f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }

        /**
         * Compress image by size, this will modify image width/height.
         * Used to get thumbnail
         *
         * @param image
         * @param pixelW target pixel of width
         * @param pixelH target pixel of height
         * @return
         */
        public static Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int options ;
            if((os.toByteArray().length / 1024) >1024){
                image.compress(Bitmap.CompressFormat.JPEG, 50, os);
                options = 50;
            }else{
                image.compress(Bitmap.CompressFormat.JPEG, 100, os);
                options = 100;
            }
            while( (os.toByteArray().length / 1024) >1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
                os.reset();//重置baos即清空baos
                Log.i("ImageUtils", "ratio: ----"+options);
                image.compress(Bitmap.CompressFormat.JPEG, options, os);//这里压缩50%，把压缩后的数据存放到baos中
                options -= 10;//每次都减少10
            }
            Log.i("ImageUtils", "ratio: --os--"+os.toByteArray().length / 1024);
            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            //开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = true;
            newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
            float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
            //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;//be=1表示不缩放
            Log.i("ImageUtils", "ratio: --w--"+w+"--h--"+h);
            Log.i("ImageUtils", "ratio: --ww--"+ww+"--hh--"+hh);
            if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
                be = (int) (newOpts.outWidth / ww);
                Log.i("ImageUtils", "ratio: --w--be-"+be);
            } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
                be = (int) (newOpts.outHeight / hh);
                Log.i("ImageUtils", "ratio: --h--be-"+be);
            }
            Log.i("ImageUtils", "ratio: --be--"+be);
            if (be <= 0) be = 1;
            newOpts.inSampleSize = be;//设置缩放比例
            //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
            is = new ByteArrayInputStream(os.toByteArray());
            bitmap = BitmapFactory.decodeStream(is, null, newOpts);
            //压缩好比例大小后再进行质量压缩
//      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
            return compressImage(bitmap);
//            return bitmap;
        }

        /**
         * Compress by quality,  and generate image to the path specified
         *
         * @param image
         * @param outPath
         * @param maxSize target will be compressed to be smaller than this size.(kb)
         * @throws IOException
         */
        public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // scale
            int options = 100;
            // Store the bitmap into output stream(no compress)
            image.compress(Bitmap.CompressFormat.JPEG, options, os);
            // Compress by loop
            while ( os.toByteArray().length / 1024 > maxSize) {
                // Clean up os
                os.reset();
                // interval 10
                options -= 10;
                image.compress(Bitmap.CompressFormat.JPEG, options, os);
            }

            // Generate compressed image file
            FileOutputStream fos = new FileOutputStream(outPath);
            fos.write(os.toByteArray());
            fos.flush();
            fos.close();
        }

        /**
         * Compress by quality,  and generate image to the path specified
         *
         * @param imgPath
         * @param outPath
         * @param maxSize target will be compressed to be smaller than this size.(kb)
         * @param needsDelete Whether delete original file after compress
         * @throws IOException
         */
        public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
            compressAndGenImage(getBitmap(imgPath), outPath, maxSize);

            // Delete original file
            if (needsDelete) {
                File file = new File(imgPath);
                if (file.exists()) {
                    file.delete();
                }
            }
        }



    /**
     * fuction: 设置固定的宽度，高度随之变化，使图片不会变形
     *
     * @param target
     * 需要转化bitmap参数
     * @param newWidth
     * 设置新的宽度
     * @return
     */
    public static Bitmap fitBitmap(Bitmap target, int newWidth)
    {
        int width = target.getWidth();
        int height = target.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) newWidth) / width;
        matrix.postScale(scaleWidth, scaleWidth);
        Bitmap bmp = Bitmap.createBitmap(target, 0, 0, width, height, matrix,
                true);
        if (target != null && !target.equals(bmp) && !target.isRecycled())
        {
            target = null;
        }
        return bmp;
    }

        /**
         * Ratio and generate thumb to the path specified
         *
         * @param image
         * @param outPath
         * @param pixelW target pixel of width
         * @param pixelH target pixel of height
         * @throws FileNotFoundException
         */
        public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
            Bitmap bitmap = ratio(image, pixelW, pixelH);
            storeImage( bitmap, outPath);
        }

        /**
         * Ratio and generate thumb to the path specified
         *
         * @param imgPath
         * @param outPath
         * @param pixelW target pixel of width
         * @param pixelH target pixel of height
         * @param needsDelete Whether delete original file after compress
         * @throws FileNotFoundException
         */
        public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
            Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
            storeImage( bitmap, outPath);

            // Delete original file
            if (needsDelete) {
                File file = new File(imgPath);
                if (file.exists()) {
                    file.delete();
                }
            }
        }

    public static Bitmap toRoundCornerUpGrades(Bitmap bitmap, int pixels, int pixelsWidth, int pixelsHeight) {
        int bitmapWidth,bitmapHeight;
        bitmapWidth =bitmap.getWidth();
        bitmapHeight =bitmap.getHeight();
        if(((float)pixelsHeight/((float)pixelsWidth))>((float)(bitmapHeight+2*pixels)/((float)bitmapWidth))||((float)pixelsHeight/((float)pixelsWidth))<(float)bitmapHeight/((float)(bitmapWidth+2*pixels))){
            return bitmap;
        }
        Bitmap output = Bitmap.createBitmap(bitmapWidth,
                bitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 头像的保存
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String fileName, String subForder) throws IOException {
//        String subForder = ConstantSet.LOCALFILEICON;
        File foder = new File(subForder);
        if (!foder.exists()) {
            SDCardUtils.makeRootDirectory(subForder);
        }
        File myCaptureFile = new File(subForder+fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
    /**
     * 图片的的保存
     * @throws IOException
     */
    //path为下载路径,saveName是保存名称可以是任何文件
    public static void getImage(String path, String subForder, String saveName) throws Exception {
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(1000 * 6);
        if (con.getResponseCode() == 200) {
            InputStream inputStream = con.getInputStream();
            byte[] b = getByte(inputStream);
            File foder = new File(subForder);
            if (!foder.exists()) {
                SDCardUtils.makeRootDirectory(subForder);
            }
            File file = new File(subForder+saveName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(b);
            fileOutputStream.close();

        }
    }

    /**
     * byte数据保存
     * @param inputStream
     * @return
     * @throws Exception
     */
    private static byte[] getByte(InputStream inputStream) throws Exception {
        byte[] b = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len = -1;
        while ((len = inputStream.read(b)) != -1) {
            byteArrayOutputStream.write(b, 0, len);
        }
        byteArrayOutputStream.close();
        inputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 读取图片名称
     * @param picturePath
     * @return
     */
    public static String getPicNameFromPath(String picturePath) {
        String temp[] = picturePath.replaceAll("\\\\", "/").split("/");
        String fileName = "";
        if (temp.length > 1) {
            fileName = temp[temp.length - 1];
        }
        return fileName;
    }

}
